package com.project.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.project.common.Constants;
import com.project.dao.IBaseDao;
import com.project.webapp.form.BaseForm;

public class BaseDaoImpl implements IBaseDao {
	public Logger log = Logger.getLogger(this.getClass());
	private SqlMapClient sqlMapClient;

	public SqlMapClient getSqlMapClient() {
		return sqlMapClient;
	}

	public void setSqlMapClient(SqlMapClient sqlMapClient) {
		this.sqlMapClient = sqlMapClient;
	}

	/**
	 * 分页查询
	 * 
	 * @param statementName
	 * @param baseForm
	 * @return
	 * @throws Exception
	 * @see com.project.dao.IBaseDao#queryWithPg(java.lang.String,
	 *      com.project.webapp.form.BaseForm)
	 */
	@SuppressWarnings("rawtypes")
	public List queryWithPg(String statementName, BaseForm baseForm)
			throws Exception {
		//获取的资料总数
		Object count = this.sqlMapClient.queryForObject(
				this.getCountQuery(statementName), baseForm);
		//System.out.println("打印出来一个值"+count.toString());
		// 资料总笔数
		String totalCount = count == null ? "0" : count.toString();
		//得到总的记录数
		int totalCountInt = Integer.parseInt(totalCount);
		//System.out.println("一共有条数据"+totalCountInt);
		// 每页显示笔数
		int countPerPage = baseForm.getCountPerPage() == 0 ? Constants.DEFAULT_MAX_PAGE_RECORD
				: baseForm.getCountPerPage();

		// 资料总页数
		String total = "";
		Integer totalInt = null;
		if (totalCountInt != 0) {
			if (totalCountInt % countPerPage == 0) {
				totalInt = totalCountInt / countPerPage;
			} else {
				totalInt = totalCountInt / countPerPage + 1;
			}
			total = totalInt + "";
		} else {
			total = "0";
		}

		// 计算从第几笔数据开始
		int startCount = 0;
		//当前页数
		String curPageNo = "0";
		if ("N".equals(baseForm.getIsFirstQuery())) {
			curPageNo = baseForm.getCurPageNo() == null ? "0" : baseForm
					.getCurPageNo();
		} else {
			baseForm.setCurPageNo("1");
		}
		//将当前页数强制转换成整形常量
		int curPageNoInt = Integer.parseInt(curPageNo);
		if (curPageNoInt != 0) {
			//取出从第几条数据开始显示
			startCount = (curPageNoInt - 1) * countPerPage;
		}
		//总的资料数
		baseForm.setTotalRecord(totalCount);
		//总页数
		baseForm.setTotal(total);
		//每页显示多少条数据
		baseForm.setCountPerPage(countPerPage);
		//记录从第几笔开始
		baseForm.setStartCount(startCount);

		List list = sqlMapClient.queryForList(statementName, baseForm);
		//System.out.println("测试工作："+statementName);
		if (list == null || list.size() == 0) {
			baseForm.setCurPageNo("0");
		}
		return list;
	}

	private String getCountQuery(String queryName) {
		return "count" + Character.toUpperCase(queryName.charAt(0))
				+ queryName.substring(1);
	}

}
